package com.fans.admin.quartz.job;

import java.util.List;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.fans.admin.quartz.constant.QtzConstant.ScheduleStatusEnum;
import com.fans.admin.quartz.entity.ScheduleJob;
import com.fans.admin.quartz.service.IScheduleJobService;
import com.fans.admin.quartz.util.ExceptionUtil;
import com.fans.admin.quartz.util.QuartzUtil;

/**
 * 服务启动执行
 *
 * @author 单红宇(365384722)
 * @myblog http://blog.csdn.net/catoop/
 * @create 2016年1月9日
 */
@Component
public class TaskStartupRunner implements CommandLineRunner {
	private Logger logger = LoggerFactory.getLogger(TaskStartupRunner.class);
	@Autowired
	private Scheduler scheduler;
	@Autowired
	private IScheduleJobService scheduleJobService;

	@Override
	public void run(String... args) throws Exception {
		System.out.println(">>>>>>>>>>>>>>>服务启动执行，执行加载定时任务<<<<<<<<<<<<<");
		init();
	}

	public void init() {
		ScheduleJob scheculeJob=new ScheduleJob();
		//scheculeJob.setJobStatus("1");
		List<ScheduleJob> scheduleJobList = scheduleJobService.findList(scheculeJob);
		
		
		if(CollectionUtils.isNotEmpty(scheduleJobList)) {
			for (ScheduleJob scheduleJob : scheduleJobList) {
				//如果是启用状态
				if(ScheduleStatusEnum.USABLE.getCode().equals(scheduleJob.getJobStatus())) {
					try {
						QuartzUtil.createScheduleJob(scheduler, scheduleJob, true);
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						logger.error("启动任务【" + scheduleJob.getJobName() + "】失败！\n" + ExceptionUtil.getStackTraceAsString(e));
					}
				} else {
					try {
						QuartzUtil.deleteScheduleJob(scheduler, scheduleJob);
					} catch (SchedulerException e) {
						// TODO Auto-generated catch block
						logger.error("删除禁用任务【" + scheduleJob.getJobName() + "】失败！\n" + ExceptionUtil.getStackTraceAsString(e));
					}
				}
			}
		}
		

//		for (ScheduleJob scheduleJob : scheduleJobList) {
//			Boolean isExistScheduler = QuartzUtil.isExistScheduler(scheduler, scheduleJob.getJobName(),
//					scheduleJob.getJobGroup());
//			try {
//				// 如果不存在，则创建
//				if (!isExistScheduler) {
//					QuartzUtil.createScheduleJob(scheduler, scheduleJob, false);
//				} else {
//					QuartzUtil.updateScheduleJob(scheduler, scheduleJob);
//				}
//			} catch (SchedulerException e) {
//				e.printStackTrace();
//			}
//		}
	}
}
